
import ApkVersionUtil from "../../Utils/ApkVersionUtil";
import LanguageMng from "../../Managers/LanguageMng";
import LanguageMngTs from "../../Managers/LanguageMngTs";
cc.Class({
    extends: cc.Component,

    properties: {
        labelName:{
            default:null,
            type:cc.Label
        },
        labelGameGold:{
            default:null,
            type:cc.Label
        },
        labelVersion:{
            default:null,
            type:cc.Label,
        },
        labelUID:{
            default:null,
            type:cc.Label
        },
        userFaceSprite:{
            default:null,
            type:cc.Sprite
        },

        userFaceBg:{
            default:null,
            type:cc.Node
        },

        activityParent:{
            default:null,
            type:cc.Node
        },

        headCoinIcon:{
            default:null,
            type:cc.Sprite
        },

        lobbyContent:{
            default:null,
            type:require("LobbyContent")
        },

        frameRupee:{
            default:null,
            type:cc.SpriteFrame
        },

        frameCoin:{
            default:null,
            type:cc.SpriteFrame
        },

        testContent:{
            default:null,
            type:cc.Node
        },
    },

    _init(){
        this.testContent.active = false
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        if (cc.sys.isNative && cc.sys.os === cc.sys.OS_ANDROID) {
            let version = cc.gg.dataMgr.version||"1.0"
            let vName = ApkVersionUtil.getApkVersionName() || ""
            this.labelVersion.string = "Version:"+version+"-"+vName
        }else if (cc.sys.isNative && cc.sys.os === cc.sys.OS_IOS) {
            let version = cc.gg.dataMgr.version||"1.0"
            let vName = ApkVersionUtil.getApkVersionName() || "ios"
            this.labelVersion.string = "Version:"+version+"-"+vName
        }else {
            this.labelVersion.string = ""
        }

        this.node.on("ui_update_people",this._onUIUpdatePeople.bind(this),this)
        this.node.on("lobby_ui_update_user",this.updateLobbyUser.bind(this),this)
        this.node.on("ui_show_test_content",this._onUIShowTestContent.bind(this),this)
        this.node.on("ui_show_activity",this._onUIShowActivity.bind(this),this)

        this.initAllCashIconInLobby()
        this._init()
        this._initBaseUI()
    },

    async _initBaseUI(){
        this.__initDaylyBonus()
    },

    async __initDaylyBonus(){
        if(!this.rewardNode) this.rewardNode = cc.find("Canvas/menu/lobby_icon_reward");
        this.rewardNode.active = false
        let result = await cc.gg.httpUtil.httpGet('/activities/list/get')
        if(!result.succ){
            cc.error(result.msg)
            return
        }

        let data = result.data
        for(let i=0;i<data.length;i++){
            let tmpData = data[i]
            if(tmpData.id == 1002){
                data = tmpData
                break
            }
        }

        let record = data.record
        if(record !== null && (record.count === 0)){

        }else {
            this.rewardNode.active = true
        }
    },

    start () {
        // this.tryToShowActivity1002()
    },

    emitEvent:function (eventName, eventData1, eventData2,eventData3) {
        this.node.emit(eventName, eventData1, eventData2, eventData3)
    },

    registeListener:function (eventName, cbFunc, target) {
        this.node.on(eventName,cbFunc, target)
    },

    initAllCashIconInLobby:function () {
        if(cc.gg.gameDataUtil.showRupee){
            this.headCoinIcon.spriteFrame = this.frameRupee
        }else {
            this.headCoinIcon.spriteFrame = this.frameCoin
        }
    },

    tryToShowActivity1002 (forceShow,cb) {
        if(cc.gg.gameDataUtil.shownDailyBonus && !forceShow){
            if(cb) cb()
            return
        }
        cc.find("Canvas").emit("msgwatcher_add",function () {
            cc.log("等待1002活动！")
            if(cc.gg.dataMgr.getPlayerInfo()){
                cc.log("显示1002活动！")
                this.doShowActivity1002(cb)
                return true
            }
            return false
        }.bind(this))
    },

    async doShowActivity1002 (cb) {
        let result = await cc.gg.httpUtil.httpGet('/activities/list/get')

        if(!result.succ){
            cc.error(result.msg)
            return
        }

        let data = result.data
        for(let i=0;i<data.length;i++){
            let tmpData = data[i]
            if(tmpData.id == 1002){
                data = tmpData
                break
            }
        }
        cc.log("get activities data:",data)
        let status = data.status
        let daysInfo = data.data
        let record = data.record
        let count = record ? record.count : 0
        let ts = record ? record.ts : 0


        // let lastGetTime = record ? record.ts : 0
        // let canCollect = cc.gg.logicUtil.canActivityCollect(lastGetTime)
        // if(!canCollect){
        //     cc.log("没有能领取的每日奖励，跳过")
        //     return
        // }

        let dailyBonusPrefab = await cc.gg.resUtil.loadRes("Activity/DailyBonus")
        if(!cc.isValid(this.node,true)){
            cc.log("大厅已经销毁，停止显示每日奖励的逻辑")
            return
        }
        let activityNode = cc.instantiate(dailyBonusPrefab)

        let activityParent = cc.find("Canvas/ActivitiesMany")
        activityParent.removeAllChildren()
        activityParent.addChild(activityNode)

        cc.gg.gameDataUtil.shownDailyBonus = true
        let bonusScript = activityNode.getComponent("DailyBonus")
        bonusScript.initDailyBonus(data,this)
        bonusScript.showDailyBonus()

        if(cb) cb()
    },
    _onUIShowActivity:function (data,showButton) {
        this.activityParent.removeAllChildren()
        cc.loader.loadRes("Activity/DailyCoin",cc.Prefab,function (err, prefab) {
            if(err){
                cc.error(err)
                return
            }
            let node = cc.instantiate(prefab)
            this.activityParent.addChild(node)
            node.getComponent("DailyCoin").initDailyCoin(data,showButton)
        }.bind(this))
    },

    // update (dt) {},

    _onUIShowTestContent:function (show) {
        cc.find("Canvas/test_content").active = show
    },

    updateLobbyUser:function () {
        let info = cc.gg.dataMgr.getPlayerInfo()
        cc.gg.logicUtil.initHead(info.img,this.userFaceSprite)
        this.userFaceBg.color = (new cc.color()).fromHEX("#"+info.face_bg)
        this._onUpdateGold(info.deposit,info.winnings)
        this._onUpdateName(info.name,info.uid)
    },

    _onUIUpdatePeople:function () {
        let data = cc.gg.dataMgr.statistics
    },

    _onUpdateVersion:function (newVersion) {
        cc.find("LobbyUINode/LabelVersion").getComponent(cc.Label).string = newVersion
    },

    showKYCScene:function () {
        // cc.gg.baseUtil.setLandscape(2)
        // cc.director.loadScene('KYC')
        cc.loader.loadRes("windows/KYC", cc.Prefab, function (err, prefab) {
            let newNode = cc.instantiate(prefab)
            cc.find("Canvas/Windows").addChild(newNode)
            cc.loader.releaseRes("windows/KYC")
        }.bind(this))
        // cc.loader.loadRes("windows/KYC", cc.Prefab, function (err, prefab) {
        //     let newNode = cc.instantiate(prefab)
        //     cc.find("Canvas/Windows").addChild(newNode)
        //     cc.loader.releaseRes("windows/KYC")
        // }.bind(this))
    },

    _onUpdateName:function (name,uid) {
        this.labelName.string = name
        this.labelUID.string = uid
    },

    _onUpdateGold:function (coin_i,coin_o) {
        let totalCoin = coin_i + coin_o
        totalCoin = cc.gg.gameDataUtil.getStringOfRupeeWithoutSymbol(totalCoin)
        this.labelGameGold.string = totalCoin
    },

    tryToShowWallet:function () {
        if(this._waitingForWallet) return
        this._waitingForWallet = true
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(cc.gg.dataMgr.getPlayerInfo()){
                this._waitingForWallet = false
                if(this._loadedWallet){
                    this._doShowWallet()
                }else {
                    cc.gg.toastMgr.showNetWaitting(function () {
                        this._doShowWallet()
                    }.bind(this))
                }
                return true
            }
            return false
        }.bind(this))
    },

    async onLobbyMenuClicked (event) {
        cc.find("Canvas/SoundManager").getComponent("SoundManager").playKaPaiSound()
        let btnName = event.target.name
        if(btnName === "lobby_icon_wallet"){
            cc.gg.logicUtil.showRegisterScene(function () {
                cc.gg.tdUtil.doSendTdEvent("show_wallet","ClickWalletButton")
                this.tryToShowWallet()
            }.bind(this))
        }else if(btnName === "lobby_icon_service"){
            this._doShowService();
        }else if(btnName === "lobby_icon_menu"){
            cc.gg.tdUtil.doSendTdEvent("click_menu","LobbyBlue")
            cc.find("Canvas/menu_content").getComponent("LobbyMenu").showRootMenu()
        }else if(btnName === "lobby_icon_rank"){
            cc.gg.tdUtil.doSendTdEvent("click_ranklist","LobbyBlue")
            let rankPrefab = await cc.gg.resUtil.loadRes("uis/Ranks")
            if(rankPrefab){
                let newNode = cc.instantiate(rankPrefab)
                cc.find("Canvas/Windows").addChild(newNode)
                let script = newNode.getComponent("RankPanelMgr")
                script.showWinRank()
            }
        }else if(btnName === "lobby_icon_reward"){
            cc.gg.tdUtil.doSendTdEvent("click_daily_bonus","LobbyBlue")
            await cc.gg.toastMgr.showNetWaitting()
            this.tryToShowActivity1002(true,function () {
                cc.gg.toastMgr.removeNetWaitting()
            })
        }
    },

    _doShowWallet:function () {
        cc.gg.baseUtil.setLandscape(2)
        cc.gg.logicUtil.showRegisterScene(function () {
            cc.loader.loadRes("windows/Wallet001",cc.Prefab,function (err, prefab) {
                cc.gg.toastMgr.removeNetWaitting()
                this._loadedWallet = true
                let newNode = cc.instantiate(prefab)
                cc.find("Canvas/Windows").addChild(newNode)
                newNode.getComponent("Wallet").initWallet(this)
                cc.loader.releaseRes("windows/Wallet001")
            }.bind(this))
        }.bind(this))
    },

    _doShowService:function () {
        cc.gg.logicUtil.showRegisterScene(function () {
            cc.loader.loadRes("windows/Service",cc.Prefab,function (err, prefab) {
                let newNode = cc.instantiate(prefab)
                cc.find("Canvas/Windows").addChild(newNode)
                cc.loader.releaseRes("windows/Service")
            }.bind(this))
        }.bind(this))
    },

    onHeadCashButtonsClicked:function (event) {
        cc.find("Canvas/SoundManager").getComponent("SoundManager").playKaPaiSound()
        let btnName = event.target.name
        if(btnName === "lobby_button_yellow"){
            cc.gg.tdUtil.doSendTdEvent("show_wallet","ClickAddCashButton")
            this.tryToShowWallet()
        }
    },

    openUserConfig:function () {
        cc.find("Canvas/SoundManager").getComponent("SoundManager").playKaPaiSound()
        if(this._loadedUserConfig){
            this._doShowUserConfig()
        }else {
            cc.gg.toastMgr.showNetWaitting(function () {
                this._doShowUserConfig()
            }.bind(this))
        }
    },

    _doShowUserConfig:function () {
        cc.loader.loadRes("windows/UserConfig",cc.Prefab,function (err, prefab) {
            cc.gg.toastMgr.removeNetWaitting()
            this._loadedUserConfig = true
            let newNode = cc.instantiate(prefab)
            cc.find("Canvas").addChild(newNode)
            newNode.getComponent("UserConfig").initUserConfig(this)
            cc.loader.releaseRes("windows/UserConfig")
        }.bind(this))
    },

    onBtnSortClicked:function (event) {
        let nowTabName = this.lobbyContent.nowTab
        if(nowTabName === "button_points"){
            cc.gg.enumConfig.reversePointRooms()
            this.lobbyContent.showOnlyOneContentNode("points",true)
            this.lobbyContent.turnSortArrowUp(cc.gg.enumConfig.reversePoint)
        }else if(nowTabName === "button_pool"){
            cc.gg.enumConfig.reversePoolRooms()
            this.lobbyContent.showOnlyOneContentNode("pool",true)
            this.lobbyContent.turnSortArrowUp(cc.gg.enumConfig.reversePool)
        }else if(nowTabName === "button_deals"){
            cc.gg.enumConfig.reverseDealRooms()
            this.lobbyContent.showOnlyOneContentNode("deals",true)
            this.lobbyContent.turnSortArrowUp(cc.gg.enumConfig.reverseDeal)
        }
    },
});
